import { addDictData, deleteDictData, queryDictDateAllList, updateDictData } from "@/services/system/SystemController";
import { ModalForm, ProFormDigit, ProFormSwitch, ProFormText } from "@ant-design/pro-components";
import { useRequest } from "@umijs/max";
import { Button, Flex, Form, message, Table, TableColumnsType, Typography } from "antd";
import { FC, useState } from "react";
import OptionBar from "@/components/OptionBar";
import ResultWrap from "@/components/ResultWrap";

const DictData: FC<{ dict_id: number }> = ({ dict_id }) => {
    let { data, loading, refresh, error } = useRequest(() => queryDictDateAllList(dict_id), { refreshDeps: [dict_id] })
    let { loading: uploading, run: upload } = useRequest((data) => editId == null ? Promise.reject("null id") : editId != 0 ? updateDictData(dict_id, editId, data) : addDictData(dict_id, data), {
        manual: true,
        throwOnError: true,
        onError(e, params) {
            message.error("操作失败")
        },
        onSuccess() {
            refresh();
            setEditId(null);
        },
    })
    const [form] = Form.useForm<System.DictDataInfo>();
    let [editId, setEditId] = useState<null | number>(null)
    const columns: TableColumnsType<System.DictDataInfo> = [
        { dataIndex: "dict_code", title: "字典键值" },
        { dataIndex: "dict_value", title: "字典标签" },
        { dataIndex: "dict_sort", title: "排序" },
        { dataIndex: "status", title: "状态", render: (v) => <Typography.Text type={v ? "success" : "danger"}>{v ? "启用" : "停用"}</Typography.Text> },
        {
            title: "操作", render: (_, record) => <OptionBar
                onDelete={async () => { await deleteDictData(dict_id, record.id); refresh(); }}
                onUpdate={() => { form.setFieldsValue(record); setEditId(record.id); }}
            />
        },
    ];
    return <>
        <Flex justify="end" > <Button type="primary" onClick={() => setEditId(0)}>新 增</Button></Flex>
        <ModalForm<System.DictDataInfo> form={form} title="字典数据" width={360} open={editId != null} layout="horizontal"
            modalProps={{ destroyOnClose: true, onCancel: () => setEditId(null) }}
            loading={uploading}
            onFinish={upload}>
            <ProFormText label="字典键值" name="dict_code" rules={[{ min: 1, max: 32, required: true }]}  ></ProFormText>
            <ProFormText label="字典标签" name="dict_value" rules={[{ min: 1, max: 32, required: true }]}  ></ProFormText>
            <ProFormDigit label="字典排序" name="dict_sort" ></ProFormDigit>
            <ProFormSwitch label="状态" name="status" ></ProFormSwitch>
        </ModalForm>
        <ResultWrap error={error} reload={refresh}>
            <Table loading={loading} dataSource={data || []} columns={columns} key={"id"} pagination={false}></Table>
        </ResultWrap>
    </>
}

export default DictData